package com.csjy.migration.hnnd.workflow;

import com.csjy.migration.hnnd.*;
import com.csjy.migration.hnnd.annotation.Dict;
import com.csjy.migration.hnnd.annotation.IdentityLinkCandidate;
import com.csjy.migration.hnnd.annotation.Task;
import com.csjy.migration.hnnd.business.*;
import com.csjy.migration.hnnd.dict.*;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;

import javax.script.ScriptException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 流程类型迁移抽象类
 */
public abstract class WorkflowMigration {
  protected DbUtil sourceDbUtil;
  protected DbUtil targetDbUtil;
  protected String projectId;
  protected String procInstId;
  protected SourceBusinessData sourceData;
  protected ProgramArgument programArgument;
  protected Map procInstRow;

  // 流程实例相关数据
  protected List<Map> jbpmTaskInstanceList = new ArrayList();
  protected List<Map> jbpmVariableInstanceList = new ArrayList<>();
  protected List<Map> wfAffixNotionObjList = new ArrayList<>();
  protected List<Map> wfFileObjList = new ArrayList<>();

  // 任务实例相关数据
  protected List<Map> taskJbpmVariableInstanceList = new ArrayList<>();
  protected List<Map> taskWfAffixNotionObjList = new ArrayList<>();
  protected List<Map> taskWfFileObjList = new ArrayList<>();

  // 当前任务实例记录
  protected String curJbpmTaskInstanceId;
  protected Map curJbpmTaskInstanceRow;
  protected Map curTaskSingleAffix = null;

  protected Map<String,String[]> curModelMap = new HashMap<>();
  protected Map<String,Object> curProcessData = new HashMap<>();
  protected Map<String,Object> curCustomData = new HashMap<>();

  // 是否正在运行中
  protected boolean isRunning = false;
  // 业务类型-附件表
  protected String curBizType;
  // 单个附件类型
  protected String curAffixType;
  // 列表附件类型
  protected String curAffixTypeCommon;
  // 流程发起人编码
  protected String applyUserId = "";
  // 下一步执行人
  protected String curNextStepUserIds = null;

  // 流程级map
  protected Map<String,Map<String,Object>> taskParamMap = new HashMap<>();
  protected Map<String,Object> actHiVarinstMap = new HashMap<>();
  protected Map<String,Map<String,String>> actHiIdentityLinkMap = new HashMap<>();
  protected Map<String,Object> procFormStrMap = new HashMap<>();

  // 流程相关通用表迁移类
  protected TPBpmLog tPBpmLog = null;
  protected NdProcessVariable ndProcessVariable = null;
  protected NdProjectAffixSubmit ndProjectAffixSubmit = null;
  protected ActHiVarinst actHiVarinst = null;
  protected ActHiIdentitylink actHiIdentityLink = null;

  // 评审结论附件对象
  protected Map reviewConclusionReportAffix = null;

  public WorkflowMigration(DbUtil sourceDbUtil, DbUtil targetDbUtil, SourceBusinessData sourceData,
                           ProgramArgument programArgument, String projectId,String procInstId, Map procInstRow) throws Exception {
    this.sourceDbUtil = sourceDbUtil;
    this.targetDbUtil = targetDbUtil;
    this.projectId = projectId;
    this.procInstId = procInstId;
    this.sourceData = sourceData;
    this.programArgument = programArgument;
    this.procInstRow = procInstRow;

    this.tPBpmLog = new TPBpmLog(sourceDbUtil,targetDbUtil,sourceData,programArgument,projectId,procInstId);
    this.ndProcessVariable = new NdProcessVariable(sourceDbUtil,targetDbUtil,sourceData,programArgument,projectId,procInstId);
    this.ndProjectAffixSubmit = new NdProjectAffixSubmit(sourceDbUtil,targetDbUtil,sourceData,programArgument,projectId,procInstId);
    this.actHiVarinst = new ActHiVarinst(sourceDbUtil,targetDbUtil,sourceData,programArgument,projectId,procInstId);
    this.actHiIdentityLink = new ActHiIdentitylink(sourceDbUtil,targetDbUtil,sourceData,programArgument,projectId,procInstId);

    init();
  }

  /**
   * 自定义初始化方法
   * @throws SQLException
   */
  public abstract void customInitData() throws SQLException, Exception;

  /**
   * 自定义插入数据方法
   * @throws Exception
   */
  public abstract void customInsertOrUpdateData() throws Exception;

  /**
   * 初始化
   * @throws SQLException
   */
  private void init() throws Exception {
    System.out.println("开始准备流程任务相关数据...");

    for(int i = 0, s = this.sourceData.getJbpmTaskInstanceList().size();i<s;i++) {
      Map jbpmTaskInstance = this.sourceData.getJbpmTaskInstanceList().get(i);
      if(!jbpmTaskInstance.get("PROCINST_").toString().equals(this.procInstId)){
        continue;
      }
      this.jbpmTaskInstanceList.add(jbpmTaskInstance);
    }

    for(int i = 0, s = this.sourceData.getJbpmVariableInstanceList().size();i<s;i++) {
      Map jbpmVariableInstance = this.sourceData.getJbpmVariableInstanceList().get(i);
      if(!jbpmVariableInstance.get("PROCESSINSTANCE_").toString().equals(this.procInstId)){
        continue;
      }
      this.jbpmVariableInstanceList.add(jbpmVariableInstance);
    }

    for(int i = 0, s = this.sourceData.getWfAffixNotionObj().size();i<s;i++) {
      Map wfAffixNotionObj = this.sourceData.getWfAffixNotionObj().get(i);
      if(!wfAffixNotionObj.get("PROCID").toString().equals(this.procInstId)){
        continue;
      }
      this.wfAffixNotionObjList.add(wfAffixNotionObj);
    }

    for(int i = 0, s = this.sourceData.getWfFileObjList().size();i<s;i++) {
      Map wfFileObj = this.sourceData.getWfFileObjList().get(i);
      if(!wfFileObj.get("PROCID").toString().equals(this.procInstId)){
        continue;
      }
      this.wfFileObjList.add(wfFileObj);
    }

    Map startWfAffixNotionObj = null;

    if(!this.wfAffixNotionObjList.isEmpty()){
      startWfAffixNotionObj = Collections.min(this.wfAffixNotionObjList,Comparator.comparing(a->{
        Object submitDate = a.get("SUBMIT_DATE");
        if(submitDate == null || submitDate.toString().equals("")) {
          submitDate = a.get("CREATE_TIME");
        }
        return (Timestamp)submitDate;
      }));
    }

    if(startWfAffixNotionObj == null ){
      this.applyUserId = null;
    } else {
      this.applyUserId = startWfAffixNotionObj.get("SUBMITEMPCODE") == null ? null: startWfAffixNotionObj.get("SUBMITEMPCODE").toString().split("\\.")[1];
    }

    System.out.println("流程任务数据准备完成.");
  }

  /**
   * 开始迁移
   * @throws Exception
   */
  public void start() throws Exception {
    System.out.println(" 准备开始迁移");

    this.actHiVarinstMap.clear();
    this.actHiIdentityLinkMap.clear();
    this.actHiIdentityLinkMap.put("process",new HashMap<String,String>());

//    this.actHiIdentityLinkMap.get("process").put("starter",);

    // 循环任务实例 根据任务实例对应的任务节点名称 选择指定的迁移方法
    Method[] methods = this.getClass().getMethods();
    Method method = null;
    Map<String,Method> methodMap = new HashMap<>();
    for (int i = 0, n = jbpmTaskInstanceList.size(); i < n; i++) {
      Map jbpmTaskInstance = jbpmTaskInstanceList.get(i);
      // 正在进行中的核保放款流程特殊处理
      if(this.procInstRow.get("WFNAME").toString().equals("item-sencor-loan-hny")){
        if(!this.procInstRow.get("OPEN_TASK_COUNT").toString().equals("0") && i > 0){
          isRunning = true;
          break;
        }
      }

      this.curJbpmTaskInstanceId = jbpmTaskInstance.get("ID_").toString();
      this.curJbpmTaskInstanceRow = jbpmTaskInstance;

      this.actHiIdentityLinkMap.put(this.curJbpmTaskInstanceId,new HashMap<String,String>());

      //初始化任务实例相关数据
      this.initTaskData();

      //调用指定方法产生运行时数据
      String taskName = jbpmTaskInstance.get("NAME_").toString();

      method = methodMap.get(taskName);

      if(method == null) {
        for (int j = 0, s = methods.length; j < s; j++) {
          Task task = methods[j].getAnnotation(Task.class);
          if (task == null) {
            continue;
          }
          if (task.value().equals(taskName)) {
            method = methods[j];
            methodMap.put(taskName, method);
            break;
          }
        }
      }

      if(method == null) {
        if(taskName.equals("task1")) {
          continue;
        } else {
          throw new Exception("节点["+taskName+"]没有对应的迁移方法.");
        }
      }

      if(jbpmTaskInstance.get("ISOPEN_").toString().equals("1")) {
        this.isRunning = true;
      }
      setActHiIdentityLink(i,method);

      try {
        method.invoke(this);
      }catch(Exception e) {
        throw new Exception("节点["+taskName+"]:"+ ((InvocationTargetException)e).getTargetException().getMessage());
      }
      this.curCustomData.put("applyUserId",applyUserId);
      this.curCustomData.put("wsgbId", this.sourceData.getWsbgAffixId());

      this.setCommonActHiVarinstData();

      //插入数据到目标数据库
      this.insertTaskData();
    }

    // 子类自定义插入或更新数据
    this.customInsertOrUpdateData();

    // 批量插入
    this.tPBpmLog.start();
    this.ndProcessVariable.migrateProcFormStr(this.getDataMapJsonString(this.procFormStrMap));
    this.ndProcessVariable.start();
    this.ndProjectAffixSubmit.setTaskParamMap(this.taskParamMap);
    this.ndProjectAffixSubmit.setBizType(this.curBizType);
    this.ndProjectAffixSubmit.start();
    this.actHiVarinst.customMigrate(this.actHiVarinstMap);
    this.actHiIdentityLink.customMigrate(this.actHiIdentityLinkMap);

    // 清空
    clearRuTaskRelatedInfo();

    System.out.println("成功清空待办任务相关信息");

    String wfName = BusinessTool.getWorkflowRealWfName(procInstRow);

    if(isRunning && !DictTool.getTargetDictCode(NewProcessDefId.class, wfName).equals(wfName)) {
      this.activeWorkflow();
    }
  }

  private void setActHiIdentityLink(int taskIdx,Method taskMethod) {
    if(this.curJbpmTaskInstanceRow.get("ACTORID_") == null || this.curJbpmTaskInstanceRow.get("ACTORID_").toString().equals("")) {
      return;
    }
    String taskActorCode = BusinessTool.getTaskRealActorId(this.curJbpmTaskInstanceRow.get("ACTORID_").toString()
        , this.curJbpmTaskInstanceRow.get("CREATE_"));
    if( taskIdx== 0) {
      this.actHiIdentityLinkMap.get("process").put("starter",taskActorCode);
    } else {
      if(taskMethod.getAnnotation(IdentityLinkCandidate.class) == null) {
        if(this.actHiIdentityLinkMap.get("process").get("participant") == null ){
          this.actHiIdentityLinkMap.get("process").put("participant", taskActorCode);
        } else {
          this.actHiIdentityLinkMap.get("process").put("participant", taskActorCode + "," + this.actHiIdentityLinkMap.get("process").get("participant"));
        }
      } else {
        this.actHiIdentityLinkMap.get(this.curJbpmTaskInstanceId).put("candidate",taskActorCode);
      }
    }
  }

  private void setCommonActHiVarinstData() {
    if(this.curJbpmTaskInstanceRow.get("END_") == null) {
      return;
    }
    Object actorId_ = this.curJbpmTaskInstanceRow.get("ACTORID_");
    if(actorId_ == null || actorId_.toString().equals("")) {
      this.actHiVarinstMap.put("lastHandleUser",null);
    } else {
      this.actHiVarinstMap.put("lastHandleUser", BusinessTool.getEmpNameByEmpCode(actorId_.toString().split("\\.")[1]));
    }
    if(!(curJbpmTaskInstanceRow.get("END_") == null || curJbpmTaskInstanceRow.get("END_").toString().equals(""))) {
      this.actHiVarinstMap.put("lastHandleTime", ((Timestamp) curJbpmTaskInstanceRow.get("END_")).toLocalDateTime().toLocalDate().toString());
    }
    this.actHiVarinstMap.put("lastHandleRemark", this.curProcessData.get("option") == null ? "" : this.curProcessData.get("option").toString());
  }

  /**
   * 回退流程
   */
  private void activeWorkflow() throws Exception {
    if(!this.procInstRow.get("WFNAME").toString().equals("item-sencor-loan-hny") && this.curJbpmTaskInstanceRow.get("ISOPEN_").toString().equals("0")) {
      throw new Exception("不能回退流程到运行状态");
    }

    Map ruJbpmTaskInstanceRow = this.curJbpmTaskInstanceRow;

    // 若当前环节是会签节点 则将所有会签节点删除掉
    String curJbpmTaskDefName = ruJbpmTaskInstanceRow.get("TASK_DEF_NAME_").toString();
    List<String> huiqianTaskDefNameList = Arrays.asList(
            "项目评审@风控责任人审核","项目评审@评审委员提交意见","项目评审@独立评审委员投票",
            "置换反担保@风控责任人审核","置换反担保@评审委员提交意见","置换反担保@独立评审委员投票",
            "项目终结流程@档案室退权证和财务处退保证金",
            "被动代偿申请@部门负责人和风控经理审批");
    if(huiqianTaskDefNameList.contains(curJbpmTaskDefName)){
      List<String> discardTaskIdList = new ArrayList<>();
      for(int i = this.jbpmTaskInstanceList.size() - 1;i>=0;i--) {
        Map jbpmTaskInstance = this.jbpmTaskInstanceList.get(i);
        if(jbpmTaskInstance.get("TASK_DEF_NAME_").toString().equals(curJbpmTaskDefName)){
          discardTaskIdList.add(jbpmTaskInstance.get("ID_").toString()+"-JW");
          continue;
        } else {
          ruJbpmTaskInstanceRow = jbpmTaskInstance;
          break;
        }
      }
      if(!discardTaskIdList.isEmpty()) {
        String discardTaskIdStr = "'"+discardTaskIdList.stream().collect(Collectors.joining("','"))+"'";
        this.targetDbUtil.updateByParams("delete from act_hi_taskinst where id_ in ("+discardTaskIdStr+")", new ArrayList());
        this.targetDbUtil.updateByParams("delete from act_hi_detail where task_id_ in ("+discardTaskIdStr+")", new ArrayList());
        this.targetDbUtil.updateByParams("delete from t_p_bpm_log where task_id in ("+discardTaskIdStr+")", new ArrayList());
        this.targetDbUtil.updateByParams("delete from nd_process_variable where task_id in ("+discardTaskIdStr+")", new ArrayList());
      }
    }

    Object actorId = ruJbpmTaskInstanceRow.get("ACTORID_");
    String taskId = ruJbpmTaskInstanceRow.get("ID_").toString();
    Object createTs = ruJbpmTaskInstanceRow.get("CREATE_");
    String processDefId = DictTool.getTargetDictCode(NewProcessDefId.class, BusinessTool.getWorkflowRealWfName(procInstRow));
    String[] taskDefNameAndKey = BusinessTool.getTaskDefNameAndKey(procInstRow,
        ruJbpmTaskInstanceRow.get("PROCDEF_NAME_").toString(),
        ruJbpmTaskInstanceRow.get("TASK_DEF_NAME_").toString());
    String taskName = taskDefNameAndKey[0];
    String taskDefKey = taskDefNameAndKey[1];
    String taskActorId = BusinessTool.getTaskRealActorId(actorId, createTs);

    //插入ACT_RU_EXECUTION
    String insertActRuExecutionSql = "INSERT INTO ACT_RU_EXECUTION\n" +
        "(ID_, REV_, PROC_INST_ID_, BUSINESS_KEY_, PARENT_ID_, PROC_DEF_ID_, SUPER_EXEC_, ACT_ID_, IS_ACTIVE_, IS_CONCURRENT_, IS_SCOPE_, IS_EVENT_SCOPE_, SUSPENSION_STATE_, CACHED_ENT_STATE_, TENANT_ID_)\n" +
        "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    List actRuExecutionValues = new ArrayList();
    //    ID_		1	NVARCHAR2(64)	[NULL]	true	[NULL]
    actRuExecutionValues.add(this.procInstId+"-JW");
    //    REV_		2	NUMBER(11,0)	[NULL]	false	[NULL]
    actRuExecutionValues.add(0);
    //    PROC_INST_ID_		3	NVARCHAR2(64)	[NULL]	false	[NULL]
    actRuExecutionValues.add(this.procInstId+"-JW");
    //    BUSINESS_KEY_		4	NVARCHAR2(255)	[NULL]	false	[NULL]
    actRuExecutionValues.add(this.procInstId+"-JW");
    //    PARENT_ID_		5	NVARCHAR2(64)	[NULL]	false	[NULL]
    actRuExecutionValues.add(null);
    //    PROC_DEF_ID_		6	NVARCHAR2(64)	[NULL]	false	[NULL]
    actRuExecutionValues.add(processDefId);
    //    SUPER_EXEC_		7	NVARCHAR2(64)	[NULL]	false	[NULL]
    actRuExecutionValues.add(null);
    //    ACT_ID_		8	NVARCHAR2(255)	[NULL]	false	[NULL]
    actRuExecutionValues.add(taskDefKey);
    //    IS_ACTIVE_		9	NUMBER(4,0)	[NULL]	false	[NULL]
    actRuExecutionValues.add(1);
    //    IS_CONCURRENT_		10	NUMBER(4,0)	[NULL]	false	[NULL]
    actRuExecutionValues.add(0);
    //    IS_SCOPE_		11	NUMBER(4,0)	[NULL]	false	[NULL]
    actRuExecutionValues.add(1);
    //    IS_EVENT_SCOPE_		12	NUMBER(4,0)	[NULL]	false	[NULL]
    actRuExecutionValues.add(0);
    //    SUSPENSION_STATE_		13	NUMBER(11,0)	[NULL]	false	[NULL]
    actRuExecutionValues.add(1);
    //    CACHED_ENT_STATE_		14	NUMBER(11,0)	[NULL]	false	[NULL]
    actRuExecutionValues.add(2);
    //    TENANT_ID_		15	NVARCHAR2(255)	[NULL]	false	[NULL]
    actRuExecutionValues.add(null);

    this.targetDbUtil.updateByParams(insertActRuExecutionSql, actRuExecutionValues, false);

    //插入ACT_RU_TASK

    String insertActRuTaskSql = "INSERT INTO ACT_RU_TASK\n" +
        "(ID_, REV_, EXECUTION_ID_, PROC_INST_ID_, PROC_DEF_ID_, NAME_, PARENT_TASK_ID_, DESCRIPTION_, TASK_DEF_KEY_, OWNER_, ASSIGNEE_, DELEGATION_, PRIORITY_, CREATE_TIME_, DUE_DATE_, CATEGORY_, SUSPENSION_STATE_, TENANT_ID_)\n" +
        "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    List actRuTaskValues = new ArrayList();
    //    ID_		1	NVARCHAR2(64)	[NULL]	true	[NULL]
    actRuTaskValues.add(taskId+"-JW");
    //    REV_		2	NUMBER(11,0)	[NULL]	false	[NULL]
    actRuTaskValues.add(0);
    //    EXECUTION_ID_		3	NVARCHAR2(64)	[NULL]	false	[NULL]
    actRuTaskValues.add(this.procInstId + "-JW");
    //    PROC_INST_ID_		4	NVARCHAR2(64)	[NULL]	false	[NULL]
    actRuTaskValues.add(this.procInstId + "-JW");
    //    PROC_DEF_ID_		5	NVARCHAR2(64)	[NULL]	false	[NULL]
    actRuTaskValues.add(processDefId);
    //    NAME_		6	NVARCHAR2(255)	[NULL]	false	[NULL]
    actRuTaskValues.add(taskName);
    //    PARENT_TASK_ID_		7	NVARCHAR2(64)	[NULL]	false	[NULL]
    actRuTaskValues.add(null);
    //    DESCRIPTION_		8	NVARCHAR2(2000)	[NULL]	false	[NULL]
    actRuTaskValues.add(null);
    //    TASK_DEF_KEY_		9	NVARCHAR2(255)	[NULL]	false	[NULL]
    actRuTaskValues.add(taskDefKey);
    //    OWNER_		10	NVARCHAR2(255)	[NULL]	false	[NULL]
    actRuTaskValues.add(null);
    //    ASSIGNEE_		11	NVARCHAR2(255)	[NULL]	false	[NULL]
    actRuTaskValues.add(taskActorId);
    //    DELEGATION_		12	NVARCHAR2(64)	[NULL]	false	[NULL]
    actRuTaskValues.add(null);
    //    PRIORITY_		13	NUMBER(11,0)	[NULL]	false	[NULL]
    actRuTaskValues.add(50);
    //    CREATE_TIME_		14	DATE	[NULL]	true	[NULL]
    actRuTaskValues.add(createTs);
    //    DUE_DATE_		15	DATE	[NULL]	false	[NULL]
    actRuTaskValues.add(null);
    //    CATEGORY_		16	NVARCHAR2(255)	[NULL]	false	[NULL]
    actRuTaskValues.add(null);
    //    SUSPENSION_STATE_		17	NUMBER(11,0)	[NULL]	false	[NULL]
    actRuTaskValues.add(1);
    //    TENANT_ID_		18	NVARCHAR2(255)	[NULL]	false	[NULL]
    actRuTaskValues.add(null);

    this.targetDbUtil.updateByParams(insertActRuTaskSql, actRuTaskValues, false);

    //插入ACT_RU_IDENTITYLINK

    String insertActRuIdentityLinkSql = "insert into ACT_RU_IDENTITYLINK(ID_, REV_, TYPE_, USER_ID_, TASK_ID_, PROC_INST_ID_, PROC_DEF_ID_)\n" +
        "SELECT ID_, 0, TYPE_, USER_ID_, TASK_ID_, PROC_INST_ID_,'"+processDefId+"' FROM ACT_HI_IDENTITYLINK WHERE PROC_INST_ID_='"
        +this.procInstId+"-JW"+"' OR TASK_ID_='"+taskId+"-JW"+"'";
    this.targetDbUtil.updateByParams(insertActRuIdentityLinkSql, new ArrayList(), false);

    //插入ACT_RU_VARIABLE
    String insertActRuVariableSql = "INSERT INTO ACT_RU_VARIABLE(ID_, REV_, TYPE_, NAME_, PROC_INST_ID_, EXECUTION_ID_, TASK_ID_, BYTEARRAY_ID_, DOUBLE_, LONG_ , TEXT_, TEXT2_)\n" +
        "SELECT ID_, REV_, VAR_TYPE_, NAME_, PROC_INST_ID_, EXECUTION_ID_, TASK_ID_, BYTEARRAY_ID_, DOUBLE_, LONG_ , TEXT_, TEXT2_ FROM ACT_HI_VARINST WHERE EXECUTION_ID_='"+this.procInstId+"-JW"+"'";
    this.targetDbUtil.updateByParams(insertActRuVariableSql, new ArrayList(), false);

    //修改其他表
    String updateActHiTaskinstSql = "update act_hi_taskinst set END_TIME_ = null where id_='"+taskId+"-JW"+"'";
    this.targetDbUtil.updateByParams(updateActHiTaskinstSql, new ArrayList(), true);

    String updateActHiProcinstSql = "update act_hi_procinst set END_ACT_ID_ = null where proc_inst_id_='"+this.procInstId+"-JW"+"' ";
    this.targetDbUtil.updateByParams(updateActHiProcinstSql, new ArrayList(), true);

    String updateNdProjectInfoWorkflowSql = "update nd_project_info_workflow set bpm_status=2 where pro_id='"+this.projectId+"' ";
    this.targetDbUtil.updateByParams(updateNdProjectInfoWorkflowSql, new ArrayList(), true);

    String deleteTPbpmLogSql = "DELETE FROM t_p_bpm_log where task_id='"+taskId+"-JW"+"' ";
    this.targetDbUtil.updateByParams(deleteTPbpmLogSql, new ArrayList(), true);
  }

  private void clearRuTaskRelatedInfo() throws SQLException {
    this.targetDbUtil.updateByParams("delete from ACT_RU_VARIABLE where proc_inst_id_ = ?"
        , Arrays.asList(this.procInstId+"-JW"));
    this.targetDbUtil.updateByParams("delete from t_p_bpm_log where BPM_ID = ? and task_id not like '%JW%' "
        , Arrays.asList(this.procInstId+"-JW"));
    this.targetDbUtil.updateByParams("delete from nd_process_variable where process_id = ? and task_id not like '%JW%' "
        , Arrays.asList(this.procInstId+"-JW"));
    this.targetDbUtil.updateByParams("delete from ACT_RU_IDENTITYLINK where proc_inst_id_ = ? or task_id_ in (select id_ from ACT_HI_TASKINST WHERE PROC_INST_ID_ = ?)"
        , Arrays.asList(this.procInstId+"-JW",this.procInstId + "-JW"));
    this.targetDbUtil.updateByParams("delete from ACT_RU_TASK where proc_inst_id_ = ?", Arrays.asList(this.procInstId+"-JW"));
    this.targetDbUtil.updateByParams("delete from ACT_RU_EXECUTION where proc_inst_id_ = ?", Arrays.asList(this.procInstId+"-JW"));
    this.targetDbUtil.updateByParams("delete from act_hi_taskinst where proc_inst_id_ = ? and id_ not like '%JW%'", Arrays.asList(this.procInstId+"-JW"));

  }
  /**
   * 初始化任务数据
   */
  private void initTaskData() throws ScriptException {

    this.curProcessData.clear();
    this.curCustomData.clear();
    this.curModelMap.clear();
    this.curTaskSingleAffix = null;
    this.curAffixType = null;
    this.curAffixTypeCommon = null;
    this.curNextStepUserIds = null;

    this.taskWfAffixNotionObjList.clear();
    this.taskWfFileObjList.clear();
    this.taskJbpmVariableInstanceList.clear();

    for(int i = 0, s = jbpmVariableInstanceList.size();i<s;i++) {
      Map jbpmVariableInstance = this.jbpmVariableInstanceList.get(i);
      if(!jbpmVariableInstance.get("TASKINSTANCE_").toString().equals(this.curJbpmTaskInstanceId)){
        continue;
      }
      this.taskJbpmVariableInstanceList.add(jbpmVariableInstance);
    }

    for(int i = 0, s = wfAffixNotionObjList.size();i<s;i++) {
      Map wfAffixNotionObj = this.wfAffixNotionObjList.get(i);
      if(!wfAffixNotionObj.get("TASKID").toString().equals(this.curJbpmTaskInstanceId)){
        continue;
      }
      this.taskWfAffixNotionObjList.add(wfAffixNotionObj);
    }

    for(int i = 0, s= wfFileObjList.size();i<s;i++) {
      Map wfFileObj = this.wfFileObjList.get(i);
      if(!wfFileObj.get("TASKID").toString().equals(this.curJbpmTaskInstanceId)){
        continue;
      }
      this.taskWfFileObjList.add(wfFileObj);
    }

    Map wfAffixNotionObjWkFlagZero = this.findFirstWfAffixNotionObjByWkflag(0);
    if(wfAffixNotionObjWkFlagZero != null) {
      Object nextStepUser = wfAffixNotionObjWkFlagZero.get("ACCEPTEMPCODE");
      if(!(nextStepUser == null || !nextStepUser.equals(""))) {
        String[] reviewSecretaryQualifiedArr = nextStepUser.toString().split(";");
        if(reviewSecretaryQualifiedArr.length == 1) {
          this.curNextStepUserIds = BusinessTool.getTaskRealActorId("HNY."+BusinessTool.getEmpCode(reviewSecretaryQualifiedArr[0])
              ,wfAffixNotionObjWkFlagZero.get("CREATE_TIME"));
        } else {
          this.curNextStepUserIds = Arrays.stream(reviewSecretaryQualifiedArr)
              .reduce("",(acc,cur)-> acc +
                  BusinessTool.getTaskRealActorId("HNY."+BusinessTool.getEmpCode(cur),wfAffixNotionObjWkFlagZero.get("CREATE_TIME")) + ",");

        }
      }

    }
  }

  /**
   * 插入数据到目标数据库
   */
  private void insertTaskData() throws JsonProcessingException, SQLException {
    if(this.curAffixTypeCommon == null || this.curAffixTypeCommon.equals("")) {
      this.curAffixTypeCommon = this.curAffixType;
    }
    Map<String,Object> taskVariableMap = new HashMap<>();
    taskVariableMap.putAll(this.curCustomData);
    taskVariableMap.putAll(this.curProcessData);
    this.tPBpmLog.customMigrate(this.curJbpmTaskInstanceRow,this.procInstRow,this.curProcessData.get("modelName"),this.getDataMapJsonString(taskVariableMap));
    this.ndProcessVariable.customMigrate(this.curJbpmTaskInstanceId, taskVariableMap);

    Map<String,Object> singleTaskMap = new HashMap<>();
    singleTaskMap.put("affixType",this.curAffixType);
    singleTaskMap.put("affixTypeCommon",this.curAffixTypeCommon);
    singleTaskMap.put("fileId",this.curCustomData.get("fileId"));
    this.taskParamMap.put(this.curJbpmTaskInstanceId,singleTaskMap);
  }

  public Map findFirstWfAffixNotionObjByWkflag(int wkflag){
    for(int i = 0, s = taskWfAffixNotionObjList.size();i<s;i++) {
      if(this.taskWfAffixNotionObjList.get(i).get("WKFLAG").toString().equals(wkflag + "")){
        return this.taskWfAffixNotionObjList.get(i);
      }
    }
    return null;
  }

  public String getJbpmVarInstValueByName(String name){
    for(int i = 0, s = taskJbpmVariableInstanceList.size();i<s;i++) {
      if(this.taskJbpmVariableInstanceList.get(i).get("NAME_").toString().equals(name)){
        return this.taskJbpmVariableInstanceList.get(i).get("STRINGVALUE_").toString();
      }
    }

    for(int i = 0,s = this.jbpmVariableInstanceList.size();i<s;i++) {
      Map t = this.jbpmVariableInstanceList.get(i);
      if((t.get("TASKINSTANCE_") == null || t.get("TASKINSTANCE_").equals("")) && t.get("NAME_").toString().equals(name)){
        return t.get("STRINGVALUE_").toString();
      }
    }
    return null;
  }

  public String getDataMapJsonString(Map<String,Object> taskVariableMap) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    // null 转换为 ""
    mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
      @Override
      public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString("");
      }
    });
    return mapper.writeValueAsString(taskVariableMap);
  }

  /**
   * 设置通用数据
   */
  public void setCommonData(boolean haveSingleProjectAffix, String singleProjectAffixId) throws Exception {

    this.setCommonProcessData();

    if(!haveSingleProjectAffix) {
      return;
    }

    Map singleAffix = null;

    // TODO: 到底是ITEMNO 等于0 还是 SORTNO等于0 还是FILEID 最小的?
    for(int i = 0, s = taskWfFileObjList.size();i<s;i++) {
      Map wfFileObj = this.taskWfFileObjList.get(i);
      if(singleProjectAffixId == null) {
        if(wfFileObj.get("SORTNO").toString().equals("0")){
          singleAffix = wfFileObj;
        }
      }else {
        if(wfFileObj.get("FILEID").toString().equals(singleProjectAffixId)){
          singleAffix = wfFileObj;
        }
      }
    }

    if(singleAffix == null) {
      return;
    }

    this.setSingleProjectAffixCustomData(singleAffix,"");
  }

  /**
   * 设置通用的流程数据
   */
  public void setCommonProcessData() throws ScriptException {
    Object reason = "";
    Object nextStepUser = "";
    String[] modelAndModelNameArr =null;

    Map wfAffixNotionObjWkFlagZero = this.findFirstWfAffixNotionObjByWkflag(0);

    // 已取消
    if(wfAffixNotionObjWkFlagZero == null ){
      return;
    }
    if(wfAffixNotionObjWkFlagZero != null) {
      reason = Tool.decodeUnicode(wfAffixNotionObjWkFlagZero.get("STRESTIMATE"));
      reason = Tool.replaceBrFlagStr(reason);
      nextStepUser = wfAffixNotionObjWkFlagZero.get("ACCEPTEMPCODE");
      modelAndModelNameArr = this.curModelMap.get(wfAffixNotionObjWkFlagZero.get("STRRESULT"));
    }

    if(modelAndModelNameArr == null) {
      modelAndModelNameArr = this.curModelMap.get("all");
      if(modelAndModelNameArr == null) {
        if(wfAffixNotionObjWkFlagZero.get("STRRESULT") != null) {
          modelAndModelNameArr = new String[]{"驳回", "驳回"};
        } else {
          modelAndModelNameArr = new String[]{"",""};
        }
      }
    }
    this.curProcessData.put("reason",reason);
    this.curProcessData.put("model",modelAndModelNameArr != null ? modelAndModelNameArr[0]:"");
    this.curProcessData.put("modelName",modelAndModelNameArr != null ? modelAndModelNameArr[1]:"");
    this.curProcessData.put("option",modelAndModelNameArr != null ? modelAndModelNameArr[1]:"");
    this.curProcessData.put("next_step_user", BusinessTool.getNextStepUser(nextStepUser, wfAffixNotionObjWkFlagZero.get("CREATE_TIME")));

    this.curProcessData.put("jwframe_model",wfAffixNotionObjWkFlagZero == null ? "" : wfAffixNotionObjWkFlagZero.get("STRRESULT"));
    this.curProcessData.put("jwframe_extcontent",wfAffixNotionObjWkFlagZero == null ? "" :wfAffixNotionObjWkFlagZero.get("EXTCONTENT"));

    this.curProcessData.put("projectId",this.projectId);
    this.curProcessData.put("pro_id",this.projectId);
    this.curProcessData.put("PRO_ID",this.projectId);


    this.curCustomData.put("projectId",this.projectId);
    this.curCustomData.put("pro_id",this.projectId);
    this.curCustomData.put("PRO_ID",this.projectId);

  }


  /**
   * 设置单个附件数据
   */
  public void setSingleProjectAffixCustomData(Map originAffix,String suffix) throws Exception {
    if(suffix == null){
      suffix = "";
    }

    String[] originalFileNameArr = null;
    double fileSize = 0;
    try {
      originalFileNameArr = originAffix.get("FILENAME").toString().split("\\.");

      BigDecimal originalFileSize = (BigDecimal)originAffix.get("FILESIZE");
      fileSize = originalFileSize.divide(BigDecimal.valueOf(1024*1024)).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
    } catch(Exception e) {
    }
    this.curCustomData.put("fileId" + suffix,originAffix == null ? "" : originAffix.get("FILEID"));
    this.curCustomData.put("fileName"+ suffix,originAffix == null ? "" : Tool.decodeUnicode(originAffix.get("FILENAME")));
    this.curCustomData.put("fileSize"+ suffix,originAffix == null ? "" : fileSize);
    this.curCustomData.put("fileType"+ suffix,originAffix == null ? "" : (originalFileNameArr.length == 2 ? originalFileNameArr[1] : ""));
    this.curCustomData.put("fileUrl"+ suffix,originAffix == null ? "" : originAffix.get("FILESTORENAME").toString());
    this.curCustomData.put("bizType"+ suffix,this.curBizType);
    this.curCustomData.put("affixType"+ suffix,this.curAffixType);

    if(suffix.equals("") ) {
      this.curCustomData.put("datagrid_ndSingleProjectAffix", originAffix == null ? "" : originAffix.get("FILEID"));
      // 临时存储当前环节的单个附件对象
      this.curTaskSingleAffix = originAffix;
    }

  }

  /**
   * 初始化任务参数map
   * @return
   */
  public Map<String,Object> initTaskParamMap() {
    Map<String,Object> map = new HashMap();
    String[] taskDefNameAndKey = BusinessTool.getTaskDefNameAndKey(procInstRow,
        curJbpmTaskInstanceRow.get("PROCDEF_NAME_").toString(),
        curJbpmTaskInstanceRow.get("TASK_DEF_NAME_").toString());
    map.put("taskDefKey", taskDefNameAndKey[1]);
    return map;
  }

  /* ==========================评审流程和更替换反担保流程通用方法==========================*/

  /**
   * 风控内勤设置D角
   */
  public void setFknqszdj() {
    //    auditSecretor	钟仲亮(huwenyuan)|华雪(huaxue)
    String[] reviewSecretaryArr = BusinessTool.getEmpCodeAndNameSeperated(this.getJbpmVarInstValueByName("auditSecretor"),"|", ",",this.curJbpmTaskInstanceRow.get("CREATE_"));
    if(reviewSecretaryArr != null && reviewSecretaryArr.length > 0) {
      this.curCustomData.put("reviewSecretaryName",reviewSecretaryArr == null ? null : reviewSecretaryArr[0]);
      this.curCustomData.put("reviewSecretary",reviewSecretaryArr == null ? null : reviewSecretaryArr[1]);
    }
    //    managerD	李志林(lizhilin)
    this.curCustomData.put("managerD",BusinessTool.getEmpCode(this.getJbpmVarInstValueByName("managerD")));
  }

  /**
   * 设置部门风控经理-评审结论
   * @throws ScriptException
   * @throws SQLException
   */
  public void setBmfkjspData() throws Exception {

    Map wfAffixNotionObj =  this.findFirstWfAffixNotionObjByWkflag(0);
    String strResult = wfAffixNotionObj == null ? "" : wfAffixNotionObj.get("STRRESULT").toString();

    if(strResult.equals("报批")) {
      // 类似审保秘书整理评审结论或评审秘书整理评审意见
      this.setPsjlData();
      // 负责人独立审批时 其他措施字段的内容
      this.curCustomData.put("conclusion",this.curProcessData.get("jwframe_extcontent") == null ?  "" :
          Tool.replaceBrFlagStr(this.curProcessData.get("jwframe_extcontent").toString().replace("其他措施=","")));
    } else {
      this.curAffixType = "tjfj";
      this.curAffixTypeCommon = this.curAffixType;
      this.setCommonData(false,null);
    }
  }

  /**
   * 设置评审投票结果
   */
  public void setVoteCustomData() {
    // 投票结果(1:通过 2:不通过 3：续议 4：补材料 5：申请上会 其中 3：续以在老流程中是没有的
    String voteResult = this.getJbpmVarInstValueByName("voteResult");
    if(voteResult == null){
      this.curCustomData.put("voting_results", "");
    } else {
      Integer voteResultInt = Integer.parseInt(voteResult);
      this.curCustomData.put("voting_results",voteResultInt <= 2 ? voteResultInt : voteResultInt + 1);
    }
    // 同意金额(万)
    this.curCustomData.put("approval_amount",this.getJbpmVarInstValueByName("extNum"));
    // 报告评级
    this.curCustomData.put("rating",this.getJbpmVarInstValueByName("maskResult"));
    // 评级说明
    this.curCustomData.put("rating_description",this.getJbpmVarInstValueByName("maskDesc"));
    // 产品名称
    this.curCustomData.put("productName",DictTool.getTargetDictCode(ProductType.class, this.sourceData.getBtItemBasic().get(0).get("PRODUCECLASS")));
    // 行业归属
    this.curCustomData.put("industry",DictTool.getTargetDictCode(Industry.class, this.sourceData.getBtItemBasic().get(0).get("AFFTRADE")));
    // 行业归属code
    this.curCustomData.put("industryCode",DictTool.getTargetDictCode(IndustryCode.class, this.sourceData.getBtItemBasic().get(0).get("AFFTRADE")));

  }

  /**
   * 设置评审结论数据
   *  适用于 评审秘书提交会议纪要 和 审保秘书汇总意见 和 部门风控经理审批(报批) 三个环节
   * @throws ScriptException
   * @throws SQLException
   */
  public void setPsjlData() throws Exception {
    this.curAffixType = "psjl";
    this.curAffixTypeCommon = this.curAffixType;
    Map wfAffixNotionObjWkFlagThree = this.findFirstWfAffixNotionObjByWkflag(3);
    this.setCommonData(true,wfAffixNotionObjWkFlagThree == null ? null : wfAffixNotionObjWkFlagThree.get("INTMARK").toString());

    // 立项评审会结论(1：通过 2：不通过)
    this.curCustomData.put("meetingConclusion",this.getJbpmVarInstValueByName("oldDecisionSetValue") == null ? "1" : this.getJbpmVarInstValueByName("oldDecisionSetValue").equals("通过") ? "1" : "2");

    // TODO: 项目基本信息(从老系统中拿)
    String[] ndProjectInfoFields = new String[] {
        "office","chiefAuditor","proType","applyCoverage","applyTime","isMicro","guaranteeRate","explain","bank"
        ,"lendingMethod","industry","industryCode","productName","customerSource","institution1","institution2"
        ,"institution3","summary","marginRatioHy","chargingMethod","revolvingLoan","everyAverageMoney"
        ,"inspectionMonths","periodsNum","guaranteeRateExtension","conclusion","creditTimeStart","creditTimeEnd"};
    getDataField(ndProjectInfoFields);
    //项目评审会结论(文字)
    this.setApprovalResultAndReviewConclusion(true);

    this.curCustomData.put("auditFileId",this.curCustomData.get("fileId"));
    this.curCustomData.put("auditFileName",this.curCustomData.get("fileName"));
    this.curCustomData.put("titleShengcheng","生成评审会结论");
    this.curCustomData.put("titlechakan","查看评审会结论");

    this.reviewConclusionReportAffix = this.curTaskSingleAffix;
  }

  /**
   * 设置评审结果和评审结论
   * @param flag
   * @throws ScriptException
   */
  public void setApprovalResultAndReviewConclusion(boolean flag) throws ScriptException {
    Map wfAffixNotionObjWkFlagOne = this.findFirstWfAffixNotionObjByWkflag(1);
    if(wfAffixNotionObjWkFlagOne == null ){
      if(flag) {
        this.curCustomData.put("applyTime","");
        this.curCustomData.put("applyCoverage","");
        this.curCustomData.put("creditTimeStart","");
        this.curCustomData.put("creditTimeEnd","");
      }
      this.curCustomData.put("reviewConclusion", "");
    } else {
      String strResultWkFlagOne = wfAffixNotionObjWkFlagOne.get("STRRESULT").toString();
      String[] strResultWkFlagOneArr = strResultWkFlagOne.split(";");
      Object[] result = Arrays.stream(strResultWkFlagOneArr).map(s->{
        String[] arr = s.split("：");
        if(arr.length == 2){
          return arr[1];
        }
        return "";
      }).toArray();
      this.curCustomData.put("applyCoverage",result[0]);
      this.curCustomData.put("applyTime",BusinessTool.convertApplyTimeToMonth(result[1]));
      this.curCustomData.put("creditTimeStart",result[2]);
      this.curCustomData.put("creditTimeEnd",result[3]);
      this.curCustomData.put("reviewConclusion",Tool.replaceBrFlagStr(Tool.decodeUnicode(wfAffixNotionObjWkFlagOne.get("STRESTIMATE").toString())));
    }

    this.curCustomData.put("marginRatioHy",this.sourceData.getRepayType());

    if(this.sourceData.getRepayType() != null) {
      if(this.sourceData.getRepayType().equals("2")) {
        this.curCustomData.put("revolvingLoan", "0");
      } else {
        this.curCustomData.put("resolvingLoan", "1");
      }
    }
    this.procFormStrMap.put("creditTimeStart",this.curCustomData.get("creditTimeStart"));
    this.procFormStrMap.put("creditTimeEnd",this.curCustomData.get("creditTimeEnd"));
    this.procFormStrMap.put("reviewConclusion",this.curCustomData.get("reviewConclusion"));
    this.setGuaranteeInfo();
  }

  /**
   * 设置出具担保意向函所需数据
   */
  public void setGuaranteeInfo() {
    if(this.curCustomData.containsKey("applyTime")) {
      this.procFormStrMap.put("applyTime", this.curCustomData.get("applyTime"));
    }
    if(this.curCustomData.containsKey("applyCoverage")) {
      this.procFormStrMap.put("applyCoverage", this.curCustomData.get("applyCoverage"));
    }
    if(this.curCustomData.containsKey("marginRatioHy")){
      this.procFormStrMap.put("marginRatioHy", this.curCustomData.get("marginRatioHy"));
    }
  }

  /**
   * 设置单个任务多用户数据
   * @param resetNextStepUser
   */
  public void setMultipleRoleIdData(boolean resetNextStepUser) {

    // nextStepUser: 曹长阳(caochangyang)
    Object nextStepUser = this.curProcessData.get("next_step_user");
    if(nextStepUser == null || nextStepUser.toString().equals("")) {
      return;
    }

    int startIdx = nextStepUser.toString().indexOf("(");
    int endIdx = nextStepUser.toString().indexOf(")");

    //    "last": "曹长阳,曾伟大",
    //    "id": "caochangyang,zengweida",

    this.curProcessData.put("id",nextStepUser.toString().substring(startIdx + 1,endIdx));
    this.curProcessData.put("last",nextStepUser.toString().substring(0,startIdx));
    if(resetNextStepUser) {
      this.curProcessData.replace("next_step_user","");
    }
    this.curCustomData.put("roleusersid",nextStepUser.toString().substring(startIdx + 1,endIdx));
    this.curCustomData.put("roleusersidlast",nextStepUser.toString().substring(0,startIdx));

  }

  /**
   * 获取档案分类
   * @return
   */
  public java.lang.String getArchiveCategory() {
    if(this.sourceData.getBtItemBasic().get(0).get("MANAGERA") == null) {
      return "B类";
    } else {
      return this.sourceData.getBtItemBasic().get(0).get("MANAGERA").toString().equals(applyUserId) ? "B类" : "A类";
    }
  }

  public void getDataField(String[] fieldArr) throws SQLException {

    Map btitembasicSingle = this.sourceData.getBtItemBasic().get(0);
    Map btEnterpriseInquiry = sourceData.getBtEnterpriseInquiryList().get(0);

    List<String> fieldArrList = Arrays.asList(fieldArr);

    if (fieldArrList.contains("office")) {
      // 事务所
      this.curCustomData.put("office", DictTool.getTargetDictCode(Office.class, btitembasicSingle.get("ACCOUNTCORP")));
    }
    if (fieldArrList.contains("chiefAuditor")) {
      //审计组长
      this.curCustomData.put("chiefAuditor", btitembasicSingle.get("ACCOUNTMAN"));
    }
    if (fieldArrList.contains("proType")) {
      //新增 ? :续保
      this.curCustomData.put("proType", btitembasicSingle.get("IS_LATEST").toString().equals("1") ? "新增项目" : "续保项目");
    }
    if (fieldArrList.contains("applyCoverage")) {
      //申请保额
      this.curCustomData.put("applyCoverage", btitembasicSingle.get("ASKASSURESUM"));
    }
    if (fieldArrList.contains("applyTime")) {
      //申请期限
      this.curCustomData.put("applyTime", BusinessTool.convertApplyTimeToMonth(btitembasicSingle.get("ASSUREIERM")));
    }
    if (fieldArrList.contains("isMicro")) {
      //是否微农贷
      this.curCustomData.put("isMicro", "");
    }
    if (fieldArrList.contains("guaranteeRate")) {
      //担保费率
      this.curCustomData.put("guaranteeRate", btitembasicSingle.get("ASSURERATE") == null ?
              null : btitembasicSingle.get("ASSURERATE").toString());
    }if (fieldArrList.contains("explain")) {
      //产品名称,地域,金额,是否贫困县信息。
      this.curCustomData.put("explain", "");
    }
    if (fieldArrList.contains("bank")) {
      //银行
      this.curCustomData.put("bank", DictTool.getTargetDictCode(Bank.class, btitembasicSingle.get("LOANBANK")));
    }
    if (fieldArrList.contains("lendingMethod")) {
      //放款方式
      this.curCustomData.put("lendingMethod", "");
    }
    if (fieldArrList.contains("industry")) {
      //从事行业
      this.curCustomData.put("industry", DictTool.getTargetDictCode(Industry.class, btEnterpriseInquiry.get("AFFTRADE")));
    }
    if (fieldArrList.contains("industryCode")) {
      //从事行业code
      this.curCustomData.put("industryCode", DictTool.getTargetDictCode(IndustryCode.class, btEnterpriseInquiry.get("AFFTRADE")));
    }
    if (fieldArrList.contains("productName")) {
      //产品名称
      this.curCustomData.put("productName", DictTool.getTargetDictCode(ProductType.class, btitembasicSingle.get("PRODUCECLASS")));
    }
    if (fieldArrList.contains("customerSource")) {
      //客户来源
      this.curCustomData.put("customerSource", "");
    }
    if (fieldArrList.contains("institution1")) {
      //客户来源：一级
      this.curCustomData.put("institution1", "");
    }
    if (fieldArrList.contains("institution2")) {
      //合作机构：二级
      this.curCustomData.put("institution2", DictTool.getTargetDictCode(InstituTion2.class, btitembasicSingle.get("EXTKIND")));
    }
    if (fieldArrList.contains("institution3")) {
      //合作机构分公司：三级
      this.curCustomData.put("institution3", "");
    }
    if (fieldArrList.contains("summary")) {
      //分析比例 ：四级
      this.curCustomData.put("summary", "");
    }
    if (fieldArrList.contains("marginRatioHy")) {
      //TODO 还款方式 获取还款表
      this.curCustomData.put("marginRatioHy", null);
    }
    if (fieldArrList.contains("chargingMethod")) {
      //收费方式
      this.curCustomData.put("chargingMethod", "");
    }
    if (fieldArrList.contains("revolvingLoan")) {
      //是否循环放款
      this.curCustomData.put("revolvingLoan", "");
    }
    if (fieldArrList.contains("everyAverageMoney")) {
      //还款计划详细(分期)
      this.curCustomData.put("everyAverageMoney", "");
    }
    if (fieldArrList.contains("inspectionMonths")) {
      //保后检查间隔月数
      this.curCustomData.put("inspectionMonths", btitembasicSingle.get("CHECKINTMONTH"));
    }
    if (fieldArrList.contains("periodsNum")) {
      // 期数
      this.curCustomData.put("periodsNum", "");
    }
    if (fieldArrList.contains("guaranteeRateExtension")) {
      //担保费率延伸字段
      this.curCustomData.put("guaranteeRateExtension", "");
    }
    if (fieldArrList.contains("conclusion")) {
      //评审会结论
      this.curCustomData.put("conclusion", "");
    }
    if (fieldArrList.contains("creditTimeStart")) {
      //授信开始时间
      if (btitembasicSingle.get("AUDITTIME") == null || btitembasicSingle.get("AUDITTIME").toString().equals("")) {
        this.curCustomData.put("creditTimeStart", null);
      } else {
        this.curCustomData.put("creditTimeStart", ((Timestamp) btitembasicSingle.get("AUDITTIME")).toLocalDateTime().toLocalDate().toString());
      }
    }
    if (fieldArrList.contains("creditTimeEnd")) {
      //授信结束时间
      if (btitembasicSingle.get("ASSUMPTIME") == null || btitembasicSingle.get("ASSUMPTIME").toString().equals("")) {
        this.curCustomData.put("creditTimeEnd", null);
      } else {
        this.curCustomData.put("creditTimeEnd", ((Timestamp) btitembasicSingle.get("ASSUMPTIME")).toLocalDateTime().toLocalDate().toString());
      }
    }
    if (fieldArrList.contains("premiumToBePaid")) {
      //代收担保费
      this.curCustomData.put("premiumToBePaid", "");
    }

  }


}
